package org.groupg.practice;

import org.jgrapht.Graph;
import org.jgrapht.alg.interfaces.ShortestPathAlgorithm;
import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class GraphThreadPoolExample {

    public static void main(String[] args) {
        // 创建一个简单的无向图
        Graph<String, DefaultEdge> graph = new SimpleGraph<>(DefaultEdge.class);

        // 添加顶点
        graph.addVertex("A");
        graph.addVertex("B");
        graph.addVertex("C");
        graph.addVertex("D");
        graph.addVertex("E");

        // 添加边
        graph.addEdge("A", "B");
        graph.addEdge("B", "C");
        graph.addEdge("C", "D");
        graph.addEdge("D", "E");
        graph.addEdge("E", "A");

        ThreadFactory customThreadFactory = new ThreadFactory() {
            private final AtomicInteger threadNumber = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("CustomThread-" + threadNumber.getAndIncrement());
                return thread;
            }
        };
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                4, 8, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), customThreadFactory);


        // 遍历图中的每个顶点，提交任务到线程池
        for (String vertex : graph.vertexSet()) {
            threadPoolExecutor.submit(() -> processVertex(vertex, graph));
        }

        // 关闭线程池并等待所有任务完成
        threadPoolExecutor.shutdown();
        try {
            threadPoolExecutor.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("所有任务处理完成！");
    }

    /**
     * 处理顶点的任务
     *
     * @param vertex 当前顶点
     * @param graph  图
     */
    private static void processVertex(String vertex, Graph<String, DefaultEdge> graph) {
        System.out.println("处理顶点: " + vertex + "，线程: " + Thread.currentThread().getName());

        // 示例任务：计算当前顶点到其他顶点的最短路径
        DijkstraShortestPath<String, DefaultEdge> dijkstra = new DijkstraShortestPath<>(graph);
        ShortestPathAlgorithm.SingleSourcePaths<String, DefaultEdge> paths = dijkstra.getPaths(vertex);

        for (String targetVertex : graph.vertexSet()) {
            if (!vertex.equals(targetVertex)) {
                System.out.println("从 " + vertex + " 到 " + targetVertex + " 的最短路径: " + paths.getPath(targetVertex));
            }
        }
    }
}